#!/bin/bash

set -xe

source /etc/lsb-release
source /RELEASE

# Download & Install GitLab
echo "deb https://packages.gitlab.com/gitlab/${PACKAGECLOUD_REPO}/ubuntu/ ${DISTRIB_CODENAME} main" > /etc/apt/sources.list.d/gitlab_${RELEASE_PACKAGE}.list
wget -q -O - https://packages.gitlab.com/gpg.key | apt-key add -
apt-get update
apt-get install -yq --no-install-recommends ${RELEASE_PACKAGE}=${RELEASE_VERSION}

# Create sshd daemon
mkdir -p /opt/gitlab/sv/sshd/supervise /opt/gitlab/sv/sshd/log/supervise
mkfifo /opt/gitlab/sv/sshd/supervise/ok /opt/gitlab/sv/sshd/log/supervise/ok
printf "#!/bin/sh\nexec 2>&1\numask 077\nexec /usr/sbin/sshd -D -f /assets/sshd_config -e" > /opt/gitlab/sv/sshd/run
printf "#!/bin/sh\nexec svlogd -tt /var/log/gitlab/sshd" > /opt/gitlab/sv/sshd/log/run
chmod a+x /opt/gitlab/sv/sshd/run /opt/gitlab/sv/sshd/log/run
mkdir -p /var/run/sshd

# Remove current gitlab.rb file
rm -f /etc/gitlab/gitlab.rb

# Patch omnibus package
patch -p0 -d /opt/gitlab < /assets/gitlab-rb-location.patch

# Create groups
groupadd -g 998 git
groupadd -g 999 gitlab-www
groupadd -g 997 gitlab-redis
groupadd -g 996 gitlab-psql
# groupadd -g 995 gitlab-ci
groupadd -g 994 mattermost
groupadd -g 993 registry

# Create accounts
useradd -m -u 998 -g git -m -s /bin/sh -d /var/opt/gitlab git
useradd -m -u 999 -g gitlab-www -m -s /bin/false -d /var/opt/gitlab/nginx gitlab-www
useradd -m -u 997 -g gitlab-redis -m -s /bin/nologin -d /var/opt/gitlab/redis gitlab-redis
useradd -m -u 996 -g gitlab-psql -m -s /bin/sh -d /var/opt/gitlab/postgresql gitlab-psql
# useradd -m -u 995 -g gitlab-ci -m -s /bin/sh -d /var/opt/gitlab/gitlab-ci gitlab-ci
useradd -m -u 994 -g mattermost -m -s /bin/sh -d /var/opt/gitlab/mattermost mattermost
useradd -m -u 993 -g registry -m -s /bin/sh -d /var/opt/gitlab/registry registry
